<template>
  <div class="file-upload-container">
    <el-upload
      ref="uploadRef"
      :action="uploadAction"
      :headers="uploadHeaders"
      :data="uploadData"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :multiple="multiple"
      :accept="accept"
      :limit="limit"
      :on-exceed="handleExceed"
      :auto-upload="autoUpload"
      :show-file-list="showFileList"
      :drag="drag"
      class="file-upload"
    >
      <div v-if="drag" class="upload-dragger">
        <el-icon class="upload-icon"><UploadFilled /></el-icon>
        <div class="upload-text">
          <p>将文件拖到此处，或<em>点击上传</em></p>
          <p class="upload-tip">{{ uploadTip }}</p>
        </div>
      </div>
      <el-button v-else type="primary" :icon="UploadFilled">
        {{ uploadText }}
      </el-button>
    </el-upload>

    <!-- 文件列表 -->
    <div v-if="fileList.length > 0" class="file-list">
      <div 
        v-for="(file, index) in fileList" 
        :key="file.uid || index"
        class="file-item"
      >
        <div class="file-info">
          <div class="file-icon">
            <el-icon v-if="getFileType(file.name) === 'image'">
              <Picture />
            </el-icon>
            <el-icon v-else-if="getFileType(file.name) === 'pdf'">
              <Document />
            </el-icon>
            <el-icon v-else-if="getFileType(file.name) === 'excel'">
              <Grid />
            </el-icon>
            <el-icon v-else-if="getFileType(file.name) === 'word'">
              <Document />
            </el-icon>
            <el-icon v-else>
              <Document />
            </el-icon>
          </div>
          <div class="file-details">
            <div class="file-name" :title="file.name">{{ file.name }}</div>
            <div class="file-meta">
              <span class="file-size">{{ formatFileSize(file.size) }}</span>
              <span v-if="file.status === 'uploading'" class="upload-progress">
                上传中 {{ file.percentage }}%
              </span>
              <span v-else-if="file.status === 'success'" class="upload-success">
                <el-icon><Check /></el-icon>
                上传成功
              </span>
              <span v-else-if="file.status === 'error'" class="upload-error">
                <el-icon><Close /></el-icon>
                上传失败
              </span>
            </div>
          </div>
        </div>
        <div class="file-actions">
          <el-button 
            v-if="file.status === 'success'" 
            type="text" 
            size="small"
            @click="handlePreview(file)"
          >
            <el-icon><View /></el-icon>
          </el-button>
          <el-button 
            type="text" 
            size="small"
            @click="handleDownload(file)"
          >
            <el-icon><Download /></el-icon>
          </el-button>
          <el-button 
            type="text" 
            size="small"
            @click="handleRemove(file)"
            class="remove-btn"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="文件预览" width="80%" center>
      <div class="preview-container">
        <img 
          v-if="previewType === 'image'" 
          :src="previewUrl" 
          class="preview-image"
          alt="预览图片"
        />
        <div v-else class="preview-other">
          <el-icon class="preview-icon"><Document /></el-icon>
          <p>{{ previewFile?.name }}</p>
          <el-button type="primary" @click="handleDownload(previewFile)">
            <el-icon><Download /></el-icon>
            下载文件
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  UploadFilled, Picture, Document, Grid, 
  Check, Close, View, Download, Delete 
} from '@element-plus/icons-vue'

export default {
  name: 'FileUpload',
  components: {
    UploadFilled,
    Picture,
    Document,
    Grid,
    Check,
    Close,
    View,
    Download,
    Delete
  },
  props: {
    modelValue: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: true
    },
    accept: {
      type: String,
      default: '.jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar'
    },
    limit: {
      type: Number,
      default: 10
    },
    maxSize: {
      type: Number,
      default: 10 * 1024 * 1024 // 10MB
    },
    autoUpload: {
      type: Boolean,
      default: false
    },
    showFileList: {
      type: Boolean,
      default: true
    },
    drag: {
      type: Boolean,
      default: false
    },
    uploadText: {
      type: String,
      default: '选择文件'
    },
    uploadTip: {
      type: String,
      default: '支持jpg/png/pdf/doc等格式，单个文件不超过10MB'
    }
  },
  emits: ['update:modelValue', 'change', 'success', 'error', 'remove'],
  setup(props, { emit }) {
    const uploadRef = ref(null)
    const fileList = ref([])
    const previewVisible = ref(false)
    const previewUrl = ref('')
    const previewType = ref('')
    const previewFile = ref(null)

    // 模拟上传配置
    const uploadAction = ref('/api/upload') // 实际项目中替换为真实API
    const uploadHeaders = ref({
      'Authorization': 'Bearer ' + (localStorage.getItem('token') || '')
    })
    const uploadData = ref({
      type: 'ticket_attachment'
    })

    // 监听modelValue变化
    watch(() => props.modelValue, (newVal) => {
      fileList.value = [...newVal]
    }, { immediate: true, deep: true })

    // 监听fileList变化
    watch(fileList, (newVal) => {
      emit('update:modelValue', newVal)
      emit('change', newVal)
    }, { deep: true })

    // 文件上传前验证
    const beforeUpload = (file) => {
      // 检查文件大小
      if (file.size > props.maxSize) {
        ElMessage.error(`文件大小不能超过 ${formatFileSize(props.maxSize)}`)
        return false
      }

      // 检查文件类型
      const fileExtension = '.' + file.name.split('.').pop().toLowerCase()
      const acceptedTypes = props.accept.split(',').map(type => type.trim())
      
      if (!acceptedTypes.includes(fileExtension)) {
        ElMessage.error(`不支持的文件类型: ${fileExtension}`)
        return false
      }

      // 检查文件数量限制
      if (fileList.value.length >= props.limit) {
        ElMessage.error(`最多只能上传 ${props.limit} 个文件`)
        return false
      }

      return true
    }

    // 上传成功处理
    const handleSuccess = (response, file) => {
      file.url = response.data?.url || URL.createObjectURL(file.raw)
      file.id = response.data?.id || Date.now()
      ElMessage.success('文件上传成功')
      emit('success', response, file)
    }

    // 上传失败处理
    const handleError = (error, file) => {
      ElMessage.error('文件上传失败: ' + (error.message || '未知错误'))
      emit('error', error, file)
    }

    // 文件移除处理
    const handleRemove = (file) => {
      ElMessageBox.confirm(
        '确定要删除这个文件吗？',
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        const index = fileList.value.findIndex(item => item.uid === file.uid)
        if (index > -1) {
          fileList.value.splice(index, 1)
        }
        emit('remove', file)
        ElMessage.success('文件已删除')
      }).catch(() => {
        // 用户取消删除
      })
    }

    // 文件预览处理
    const handlePreview = (file) => {
      if (file.url) {
        previewUrl.value = file.url
        previewType.value = getFileType(file.name)
        previewFile.value = file
        previewVisible.value = true
      } else {
        ElMessage.warning('文件预览不可用')
      }
    }

    // 文件下载处理
    const handleDownload = (file) => {
      if (file.url) {
        const link = document.createElement('a')
        link.href = file.url
        link.download = file.name
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } else {
        ElMessage.warning('文件下载不可用')
      }
    }

    // 文件数量超出限制处理
    const handleExceed = (files, fileList) => {
      ElMessage.warning(`最多只能上传 ${props.limit} 个文件，当前选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    }

    // 获取文件类型
    const getFileType = (fileName) => {
      const extension = fileName.split('.').pop().toLowerCase()
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
      const pdfTypes = ['pdf']
      const excelTypes = ['xls', 'xlsx']
      const wordTypes = ['doc', 'docx']
      
      if (imageTypes.includes(extension)) return 'image'
      if (pdfTypes.includes(extension)) return 'pdf'
      if (excelTypes.includes(extension)) return 'excel'
      if (wordTypes.includes(extension)) return 'word'
      return 'other'
    }

    // 格式化文件大小
    const formatFileSize = (size) => {
      if (size < 1024) return size + ' B'
      if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
      if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(1) + ' MB'
      return (size / (1024 * 1024 * 1024)).toFixed(1) + ' GB'
    }

    // 手动上传
    const submit = () => {
      if (uploadRef.value) {
        uploadRef.value.submit()
      }
    }

    // 清空文件列表
    const clearFiles = () => {
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
      fileList.value = []
    }

    // 暴露方法给父组件
    const expose = {
      submit,
      clearFiles
    }

    return {
      uploadRef,
      fileList,
      previewVisible,
      previewUrl,
      previewType,
      previewFile,
      uploadAction,
      uploadHeaders,
      uploadData,
      beforeUpload,
      handleSuccess,
      handleError,
      handleRemove,
      handlePreview,
      handleDownload,
      handleExceed,
      getFileType,
      formatFileSize,
      ...expose
    }
  }
}
</script>

<style scoped>
.file-upload-container {
  width: 100%;
}

.file-upload {
  width: 100%;
}

.upload-dragger {
  width: 100%;
  height: 180px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-dragger:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-text {
  text-align: center;
  color: #606266;
}

.upload-text p {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
}

.upload-tip {
  font-size: 14px;
  color: #909399;
}

.file-list {
  margin-top: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafbfc;
  max-height: 300px;
  overflow-y: auto;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  transition: all 0.2s ease;
}

.file-item:last-child {
  border-bottom: none;
}

.file-item:hover {
  background: #f5f7fa;
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.file-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f2f5;
  border-radius: 6px;
  margin-right: 12px;
  flex-shrink: 0;
}

.file-icon .el-icon {
  font-size: 18px;
  color: #606266;
}

.file-details {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 4px;
}

.file-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.file-size {
  color: #606266;
}

.upload-progress {
  color: #409eff;
}

.upload-success {
  color: #67c23a;
  display: flex;
  align-items: center;
  gap: 4px;
}

.upload-error {
  color: #f56c6c;
  display: flex;
  align-items: center;
  gap: 4px;
}

.file-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-shrink: 0;
}

.file-actions .el-button {
  padding: 4px;
  min-height: auto;
}

.remove-btn {
  color: #f56c6c;
}

.remove-btn:hover {
  color: #f56c6c;
  background: #fef0f0;
}

.preview-container {
  text-align: center;
  max-height: 70vh;
  overflow: auto;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.preview-other {
  padding: 40px;
}

.preview-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.preview-other p {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .upload-dragger {
    height: 120px;
  }
  
  .upload-icon {
    font-size: 32px;
  }
  
  .upload-text p {
    font-size: 14px;
  }
  
  .file-item {
    padding: 8px 12px;
  }
  
  .file-icon {
    width: 24px;
    height: 24px;
    margin-right: 8px;
  }
  
  .file-name {
    font-size: 13px;
  }
  
  .file-meta {
    font-size: 11px;
    gap: 8px;
  }
}
</style>
